package com.wolfsea.viewpager2demo.ui.define
import android.content.Context
import android.graphics.Camera
import android.graphics.Canvas
import android.graphics.Matrix
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout

/**
 *@desc  ConstraintLayout
 *@author liuliheng
 *@time 2022/3/20  18:27
 **/
class DIYConstraintLayout : ConstraintLayout {

    private var rotateY = 0F
    private var isLeftRotate = true

    private var diyMatrix = Matrix()
    private var diyCamera = Camera()

    constructor(context: Context) : super(context)

    constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet)

    constructor(context: Context, attributeSet: AttributeSet?, defaultResId: Int) : super(
        context,
        attributeSet,
        defaultResId
    )

    override fun dispatchDraw(canvas: Canvas?) {

        //保存状态
        diyCamera.save()
        //设置旋转角度
        diyCamera.rotateY(rotateY)
        //将变换应用到Canvas上
        diyCamera.applyToCanvas(canvas)

        diyCamera.getMatrix(diyMatrix)

        if (!isLeftRotate) {
           //靠左旋转
            diyMatrix.preTranslate(-width.toFloat(), -(height.shr(1).toFloat()))
            diyMatrix.postTranslate(width.toFloat(), (height.shr(1).toFloat()))
        } else {
            //靠右旋转
            diyMatrix.preTranslate(0F, -(height.shr(1).toFloat()))
            diyMatrix.postTranslate(0F, (height.shr(1).toFloat()))
        }

        canvas?.setMatrix(diyMatrix)
        //camera恢复状态
        diyCamera.restore()

        super.dispatchDraw(canvas)
    }


    fun updateRotateY(rotateY: Float) {
        this.rotateY = rotateY
        invalidate()
    }

    fun updateIsLeftRotate(isLeftRotate: Boolean) {
        this.isLeftRotate = isLeftRotate
    }

}